package com.quasar.hpatient.view.message;

import android.graphics.Color;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.model.httpmodel.AnotherResult;
import com.quasar.hpatient.model.httpmodel.DataStateResult;
import com.quasar.hpatient.model.medicalmodel.FriendsData;
import com.quasar.hpatient.model.medicalmodel.PushinfoData;
import com.quasar.hpatient.model.medicalmodel.SelectFriendsData;
import com.quasar.hpatient.onInterface.OnFriendListener;
import com.quasar.hpatient.onInterface.OnJpshListener;
import com.quasar.hpatient.presenter.JpshPresenter;
import com.quasar.hpatient.presenter.NewsFriendPresenter;
import com.quasar.hpatient.utils.MsgJumpView;
import com.quasar.hpatient.view.adapter.MessageAdapter;
import com.quasar.hpatient.view.fragment.DoctorFragment;
import com.quasar.hpatient.view.friends.NewsFriendActivity_;
import com.quasar.hpatient.widget.MyView;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;


/**
 * 我的消息
 */
@EActivity(R.layout.activity_my_message)
public class MyMessageActivity extends BaseActivity implements OnJpshListener, BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener,OnFriendListener {


    private JpshPresenter jpshPresenter;
    //分页
    int page=1;
    private MessageAdapter messageAdapter;
    //判断下一页是否存在数据
    private boolean onLoadMore=false;
    private int delayMillis = 1000;//设置刷新等待的时间
    private NewsFriendPresenter newsFriendPresenter;

    @ViewById(R.id.main_toolbar)
    Toolbar main_toolbar;
    @ViewById(R.id.mv_comm)
    MyView mv_comm;
    @ViewById(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @ViewById(R.id.rv_list)
    RecyclerView rv_list;

    private final String ADDTO = "2";//添加
    private final String REFUSE = "1";//拒绝

    int postion=0;

    @AfterViews
    void init(){
        initView();
        initData();
    }

    @Override
    protected void initView() {
        initToolbar();
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeColors(Color.rgb(47, 223, 189));
        rv_list.setLayoutManager(new LinearLayoutManager(this));
    }

    @Override
    protected void initData() {
        jpshPresenter=new JpshPresenter(this);
        newsFriendPresenter=new NewsFriendPresenter(this);
        initJpshAdapter();
    }

    //初始化adapter布局
    public void initJpshAdapter() {
        messageAdapter=new MessageAdapter();
        messageAdapter.setOnLoadMoreListener(this, rv_list);
        jpshPresenter.GetUserLatestMessageData(page+"");
        rv_list.setAdapter(messageAdapter);

        messageAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                switch (view.getId()){
                    case R.id.look://查看消息
                        jpshPresenter.UpdateUserMessage(messageAdapter.getItem(position).getId()+"");
                        MsgJumpView.JumpView(MyMessageActivity.this,messageAdapter.getData().get(position).getMessageType()+"",
                                messageAdapter.getData().get(position).getTestTime().substring(0,10));

                        ViseLog.d("点击的查看消息"+messageAdapter.getData().get(position).getLogTime());
                        break;
                    case R.id.apply://同意
                        newsFriendPresenter.operationFriend(messageAdapter.getData().get(position).getSendId() + "", ADDTO);
                        postion=messageAdapter.getData().get(position).getId();
                        break;

                    case R.id.Refuse://拒绝
                        newsFriendPresenter.operationFriend(messageAdapter.getData().get(position).getSendId() + "", REFUSE);
                        postion=messageAdapter.getData().get(position).getId();
                        break;
                }
            }
        });
    }

    //交流消息
    @Click(R.id.mv_comm)
    public void mv_comm(){
        CommunicationActivity_.intent(this).start();
    }

    //好友消息
    @Click(R.id.mv_msg)
    public void mv_msg(){
        NewsFriendActivity_.intent(this).start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateUnreadLabel();
    }

    /**
     *  获取环信未读消息数量
     * 消息数量
     * update unread message count
     */

    public void updateUnreadLabel() {
        int count = getUnreadMsgCountTotal();
        mv_comm.setNum(count);
    }
    /**
     * get unread message count
     *
     * @return
     */

    public int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        int chatroomUnreadMsgCount = 0;
        unreadMsgCountTotal = EMClient.getInstance().chatManager().getUnreadMessageCount();
        for (EMConversation conversation : EMClient.getInstance().chatManager().getAllConversations().values()) {
            if (conversation.getType() == EMConversation.EMConversationType.ChatRoom)
                chatroomUnreadMsgCount = chatroomUnreadMsgCount + conversation.getUnreadMsgCount();
        }
        return unreadMsgCountTotal - chatroomUnreadMsgCount;
    }

    @Override
    public void onJpshSuccess(AnotherResult<PushinfoData> data) {

        //判断page是否是下拉还是上拉
        if(page==1){
            messageAdapter.setNewData(data.getList());
            onLoadMore=false;
        }else{
            messageAdapter.addData(data.getList());
            if(data.getList().size()==0){
                onLoadMore=true;
            }
        }
    }

    @Override
    public void onJpshError(String msg) {

        if (msg!=null){
            msg(msg);
        }
    }

    @Override
    public void onJpshRefreshUI() {

    }

    @Override
    public void onLookSuccessMsg(DataStateResult dataStateResult) {
        if(dataStateResult.getMsgCode().equals("0x00000000")){
            onRefresh();
        }
    }

    @Override
    public void onVisitMessageSuccess(AnotherResult<PushinfoData> data) {

    }

    @Override
    public void onRefresh() {
        ViseLog.d("onRefresh");
        page=1;
        jpshPresenter.GetUserLatestMessageData(page+"");
        messageAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //下拉后添加新数据
                swipeLayout.setRefreshing(false);//下拉刷新关闭
                messageAdapter.setEnableLoadMore(true);
            }
        }, delayMillis);
    }

    @Override
    public void onLoadMoreRequested() {
        page++;//下拉时page递增
        jpshPresenter.GetUserLatestMessageData(page+"");
        rv_list.postDelayed(new Runnable() {
            @Override
            public void run() {
                //判断当返回的数据为空时停止下拉刷新
                if (onLoadMore) {
                    messageAdapter.loadMoreEnd();
                } else {
                    messageAdapter.loadMoreComplete();
                    messageAdapter.notifyDataSetChanged();
                }
            }

        }, delayMillis);
    }

    @Override
    public void onSuccess(DataStateResult data) {

    }

    @Override
    public void onError(String msg) {

    }

    @Override
    public void onRefreshUI() {

    }

    @Override
    public void onNewsFriendSuccess(AnotherResult<FriendsData> data) {

    }

    //添加好友成功
    @Override
    public void onNewsFriendRefreshUI(DataStateResult data) {

        if (data.getMsgCode().equals("0x00000000")) {
            msg("操作成功");
            jpshPresenter.UpdateUserMessage(messageAdapter.getData().get(postion).getId()+"");
        }
    }

    @Override
    public void searchFriend(SelectFriendsData selectFriendsData) {

    }

    @Override
    public void onAddtoFriend(DataStateResult dataStateResult) {

    }
}
